import "../../css/order.css"
import { useEffect, useState } from "react";
import { GetOrderStatistics, GetOrders } from "../../api/order";
import { Button, Input, Space, Table, Tag, Divider, Pagination, Spin, Checkbox, Skeleton, Modal, DatePicker } from "antd"
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';


import React from 'react';

const Order = () => {
    const [loading, setLoading] = React.useState(false);
    const [isComplete, setIsComplete] = useState(-1);
    const [isCancel, setIsCancel] = useState(-1);
    const [isDirectly, setIsDirectly] = useState(-1);


    const PAGE_SIZE = 5;// 设置每页显示的数据条数

    const [currentPage, setCurrentPage] = useState(1);//当前页
    const [total, setTotal] = useState(0); // 定义total变量
    const [searchKeyword, setSearchKeyword] = useState('');//搜索关键字
    const { RangePicker } = DatePicker;
    const [visible, setVisible] = useState(false); // 控制模态框的显示与隐藏  
    const [data, setData] = useState([]); // 假设这是你要导出的数据  
    const [shows, setShows] = useState(true);//骨架屏

    const showModal = () => {
        // fetchData(); // 在显示模态框前获取数据  
        setVisible(true); // 显示模态框  
    };
    const handleOk = async () => {
        try {
            // 获取数据  
            const res = await GetOrders({
                page: currentPage,
                limit: PAGE_SIZE,
                isComplete: isComplete,
                isCancel: isCancel,
                isDirectly: isDirectly,
            });

            if (res.result === 0) {
                const data = res.data.data || [];

                // 将数据转换为工作簿对象  
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.aoa_to_sheet(data);

                // 将工作表添加到工作簿  
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

                // 将工作簿转换为blob对象  
                const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
                const blob = new Blob([wbout], { type: 'application/octet-stream' });

                // 使用file-saver保存文件  
                saveAs(blob, 'data.xlsx');
            } else {
                console.error('获取数据失败:', res.message);
            }
        } catch (error) {
            console.error('导出失败:', error);
        } finally {
            setVisible(false);
        }
    };

    const handleCancel = () => {
        // 处理模态框取消按钮的点击事件  
        setVisible(false); // 隐藏模态框 
    };

    const handlePageChange = (page) => {
        setCurrentPage(page);
        bindorder();
    };

    const navigate = useNavigate()

    //获取订单统计数据
    const [OrderStatistics, setOrderStatistics] = useState([]);
    const bindOrder = async () => {
        setLoading(true)
        const res = await GetOrderStatistics();
        if (res.result === 0) {
            setOrderStatistics(res.data)
            setLoading(false)
            
        }
    }
    useEffect(() => {
        bindOrder();
    }, [])

    const check = (val) => {
        console.log(val);
        for (let i = 0; i < val.length; i++) {
            if (parseInt(val[i]) === 1) {
                setIsComplete(1);
            };
            if (parseInt(val[i]) === 2) {
                setIsCancel(1);
            };
            if (parseInt(val[i]) === 3) {
                setIsDirectly(1);
            };
        }
        if (val.length === 0) {
            setIsComplete(-1);
            setIsCancel(-1);
            setIsDirectly(-1);
        }
        // bindorder();
    }

    // 获取订单列表
    const [orders, setOrders] = useState([]);
    const bindorder = async () => {
        setLoading(true)
        const res = await GetOrders(
            {
                page: currentPage,
                limit: PAGE_SIZE,
                key: searchKeyword,
                isComplete: isComplete,
                isCancel: isCancel,
                isSend: -1,
                isDirectly: isDirectly,
            }
        );
        if (res.result === 0) {
            setOrders(res.data.data)
            setTotal(res.data.total)
            setLoading(false)
            setShows(false);
        }
    }
    useEffect(() => {
        bindorder();
    }, [currentPage, searchKeyword, isComplete, isDirectly, isCancel])

    // 获取订单列表
    const order = [
        {
            title: '订单号',
            dataIndex: 'id',
            key: 'id',
            ellipsis: true,
            width: 165
        },
        {
            title: '商户',
            dataIndex: 'merchant',
            ellipsis: true,
        },
        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            render: (_, record) => (
                <>
                    <Tag color={record.supplier == null ? "error" : "blue"} > {record.supplier === null ? '自营' : record.supplier}</Tag>
                </>
            ),
        },
        {
            title: '种类',
            dataIndex: 'goodsCategory',
            render: (val, i) => (
                <>
                    <Tag color="processing">{val}</Tag>
                </>
            )
        },
        {
            title: '金额',
            dataIndex: 'money',
            render: (val, i) => (
                <>
                    <Tag color="processing">{val}</Tag>
                </>
            )
        },
        {
            title: '状态',
            dataIndex: 'isComplete',
            render: (_, { isComplete, isCancel }) => isComplete === 1 ? <Tag color="success">
                已完成
            </Tag> : isCancel === 1 ? <Tag>
                已取消
            </Tag> : <Tag color="orange">
                未完成
            </Tag>
        },
        {
            title: '时间',
            dataIndex: 'time',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'address',
            width: '250px',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        ghost
                        onClick={() => detail(record)}
                    >详情</Button>
                </Space>
            ),
        },
    ];

    const detail = (val) => {
        navigate('/order/Detail/' + val.id)
    }

    return (
        <div className="order-exam-container">
            <Skeleton loading={shows} active={true} paragraph={{ rows: 10 }} rows={20} style={{ padding: '10px' }}>
                <Spin spinning={loading} delay={500}>
                    <div className="">
                        <div className="">
                            <div className="order-index">
                                <div className="order-exam-container1">
                                    <div className="orders">
                                        <span className="order-counts1">订单总数,{OrderStatistics.orderCount}</span>
                                        <Divider style={{ backgroundColor: "#fff" }} />
                                        <span className="order-amount1">有效订单,{OrderStatistics.validOrderCount}</span>
                                    </div>
                                </div>

                                <div className="order-exam-container2">
                                    <div className="orders">
                                        <span className="order-counts2">有效金额,{OrderStatistics.orderMoney}</span>
                                        <Divider style={{ backgroundColor: "#fff" }} />
                                        <span className="order-amount2">商品数量,{OrderStatistics.goodsCount}</span>
                                    </div>
                                </div>

                                <div className="order-exam-container3">
                                    <div className="orders">
                                        <span className="order-counts3">下单人数,{OrderStatistics.orderPeople}</span>
                                        <Divider style={{ backgroundColor: "#fff" }} />
                                        <span className="order-amount3">商品种类,{OrderStatistics.goodsCategory}</span>
                                    </div>
                                </div>

                                <div className="order-exam-container4">
                                    <div className="orders">
                                        <span className="order-counts4">完成订单数,{OrderStatistics.completeOrderCount}</span>
                                        <Divider style={{ backgroundColor: "#fff" }} />
                                        <span className="order-amount4">发货订单数,{OrderStatistics.sendOrderCount}</span>
                                    </div>
                                </div>
                            </div>
                            <div className="exam-container">
                                <div className="button">
                                    <div className="box-button1">
                                        <Button type="primary" onClick={showModal}>数据导出</Button>
                                        <Modal
                                            title="数据导出"
                                            visible={visible} // 控制模态框的显示与隐藏  
                                            onOk={handleOk}
                                            onCancel={handleCancel}
                                            okText="确定导出" // 设置确定按钮的文本为“确定”  
                                            cancelText="取消" // 设置取消按钮的文本为“取消”
                                            mask={false}
                                        >
                                            <Checkbox.Group onChange={check}>
                                                <Checkbox value={1}>已完成</Checkbox>
                                                <Checkbox value={2}>已取消</Checkbox>
                                                <Checkbox value={3}>直营订单</Checkbox>
                                            </Checkbox.Group>
                                            <RangePicker placeholder={['', '']} defaultValue={[
                                                moment().startOf('day'), // 当前日期的开始时间（今天凌晨）  
                                                moment().endOf('day').add(1, 'months')  // 当前日期的结束时间（今天晚上11点59分） .add(40, 'days')  
                                            ]} style={{ width: '100%' }} />
                                        </Modal>
                                    </div>
                                    <div className='box-button2'>
                                        <Space.Compact
                                            style={{
                                                width: '100%',
                                                height: '40px'
                                            }}
                                        >
                                            <Input placeholder="根据订单号搜索" value={searchKeyword}
                                                onChange={(e) => setSearchKeyword(e.target.value)} />
                                            <Button type="primary" ghost style={{ height: '40px' }}>搜索</Button>
                                        </Space.Compact>
                                    </div>
                                    <div>
                                        <Checkbox.Group onChange={check}>
                                            <Checkbox value={1}>已完成</Checkbox>
                                            <Checkbox value={2}>已取消</Checkbox>
                                            <Checkbox value={3}>直营订单</Checkbox>
                                        </Checkbox.Group>
                                    </div>
                                </div>
                            </div>
                            <div className="table">
                                <Table
                                    columns={order}
                                    dataSource={orders}
                                    bordered
                                    pagination={false}
                                    scroll={{
                                        x: 1000,
                                    }}
                                />
                            </div>
                            {/* <Pagination current={currentPage} total={total} pageSize={PAGE_SIZE} onChange={handlePageChange} className="pagination" /> */}
                            <Pagination current={currentPage} total={total} pageSize={PAGE_SIZE} onChange={handlePageChange} className="pagination" />
                        </div>
                    </div>
                </Spin>
            </Skeleton>
        </div>
    )
}

export default Order